package lintulaskenta.utils;

import com.sun.org.apache.xerces.internal.util.URI;
import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class TipuApiClientForInterface {

    private DefaultHttpClient httpclient;

    public TipuApiClientForInterface() throws URISyntaxException, MalformedURIException {
        // Salasanatiedoston sijainti
        File file = new File("/Users/jukkapajunen/Documents/Koulu/OhTuProje/tipu-apin_passut.txt");
        Scanner scanner;
        try {
            scanner = new Scanner(file);
            String uri2 = scanner.next();
            String username = scanner.next();

            String password = scanner.next();
            URI uri = new URI(uri2);
            httpclient = new DefaultHttpClient();
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password));
        } catch (FileNotFoundException ex) {
            System.out.println("Tiedostoa ei löydy");
        }
    }

    // Metodilla haetaan kunnat ja havainnoijat
    public ArrayList getAsDocument(String uri, String tagName) throws Exception {
        HttpPost httppost = new HttpPost(uri);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(instream);

        doc.getDocumentElement().normalize();

        NodeList nodeLst = doc.getElementsByTagName(tagName);
        TreeMap<String, String> lista = new TreeMap<String, String>();
        ArrayList<Item> lista2 = new ArrayList<Item>();
        for (int s = 0; s < nodeLst.getLength(); s++) {
            Element e = (Element) nodeLst.item(s);
            String id = (String) getTextValue(e, "id");
            if (id.length() > 6) {
                id = id.substring(0, 6);
            }
            String name = (String) getTextValue(e, "name");
            if (!lista.containsKey(id)) {
                lista.put(id, name);
                lista2.add(new Item(id, name));
            }
        }
        return lista2;
    }

    // Metodilla haetaan rengastajat
    public ArrayList<Item> getRingers(String uri, String tagName) throws Exception {
        HttpPost httppost = new HttpPost(uri);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(instream);
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName(tagName);
        ArrayList<Item> lista = new ArrayList<Item>();

        for (int s = 0; s < nodeList.getLength(); s++) {
            Node nNode = (Node) nodeList.item(s);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                String id = getTagValue("id", eElement);
                String firstname = getTagValue("firstname", eElement).trim();
                String lastname = getTagValue("lastname", eElement).trim();
                String name = "";
                if (firstname.length() > 0 && lastname.length() > 0) {
                    name = lastname + " " + firstname;
                } else {
                    name = lastname + firstname;
                }
                lista.add(new Item(id, name));
            }
        }
        return lista;
    }

    private String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

        Node nValue = (Node) nlList.item(0);
        if (nValue == null) {
            return "";
        }
        return nValue.getNodeValue();
    }

    private String getTextValue(Element ele, String tagName) {
        String textVal = null;
        NodeList nl = ele.getElementsByTagName(tagName);
        if (nl.item(0) != null) {
            Element el = (Element) nl.item(0);

            if (el.getFirstChild() != null) {
                textVal = el.getFirstChild().getNodeValue();
            } else {
                el = (Element) nl.item(3);
                textVal = el.getFirstChild().getNodeValue();
            }
        }

        return textVal;
    }
}
